'''
Created on Jun 16, 2010

@author: oabalbin
'''
import os
import copy
import glob
import numpy as np
from RNAseq.common.ordereddict import OrderedDict
from collections import deque, defaultdict
from RNAseq.common.classes import myArray


def read_list_genes(inputfile):
    """
    Read panther gene list
    """
    genlist=defaultdict()
    for line in inputfile:        
        line = line.strip('\n')
        fields = line.split(';')
        #print fields 
        # To skip headers, star reading samples in column 7 of the file
        if fields[0][0] == '#': 
            continue                             
        if fields[0]=='':
            continue
        genlist[fields[1]] = fields[0]
    
    return genlist

def read_list_genes2(inputfile):
    """
    Read panther gene list
    """
    genlist=defaultdict()
    for line in inputfile:        
        line = line.strip('\n')
        fields = line.split('\t')
        #print fields 
        # To skip headers, star reading samples in column 7 of the file
        if fields[0][0] == '#': 
            continue                             
        if fields[0]=='':
            continue
        genlist[fields[0]] = fields[1]
    
    return genlist

def read_list_genes3(inputfile):
    """
    Read panther gene list
    """
    genlist=defaultdict()
    for line in inputfile:        
        line = line.strip('\n')
        fields = line.split('\t')
        #print fields 
        # To skip headers, star reading samples in column 7 of the file
        if fields[0][0] == '#': 
            continue                             
        if fields[0]=='':
            continue
        genenames=fields[1].split('///')
        print fields 
        for gene in genenames:
            gene.strip()
            genlist[gene] = fields[0]
            
    return genlist


def list_of_names(inputfile):
        
        genlist=deque()
        for line in inputfile:        
            line = line.strip('\n')
            fields = line.split('\t')
            #print fields 
            # To skip headers, star reading samples in column 7 of the file
            if fields[0][0] == '#': 
                continue                             
            if fields[0]=='':
                continue
            
            genlist.append(fields[0])
        
        return genlist


def read_sample_list(inputfile):
        ''' Input: file with 2 sample list. Each list for row
        '''
        treatment_sample_list=[]
        normal_sample_list=[]
        for line in inputfile:
            if line.startswith('#'):
                fields = line.strip('\n').split('\t')
                if fields[0]=='#Control':
                    normal_sample_list=fields[1:]
                else:
                    treatment_sample_list=fields[1:]
                    
        return treatment_sample_list, normal_sample_list



def dict_of_names(inputfile):
        
        genlist=defaultdict()
        i=0
        for line in inputfile:        
            line = line.strip('\n')
            fields = line.split('\t')
            #print fields 
            # To skip headers, star reading samples in column 7 of the file
            if fields[0][0] == '#': 
                continue                             
            if fields[0]=='':
                continue
            
            genlist[fields[0]]=i
            i+=1
        
        return genlist
    

def create_array4subset_genes(thisGeneArray, genelist):
    """
    Returns a sub-structure myArray using the genelist
    """
    notfound=[]
    new_gendict = defaultdict()
    new_genIntr = defaultdict()
    #common_genes = new_gene_set.intersection(set(thisGeneArray.gendict.values()))
    for i, gen in thisGeneArray.gendict.iteritems():
        try:
            genelist[gen]
            new_gendict[i] = gen
            new_genIntr[i] = thisGeneArray.genInterval[i]
        except KeyError:
            notfound.append(gen)
    
    newExpVal = thisGeneArray.expVal[new_gendict.keys(),:]
    newsampledict = copy.copy(thisGeneArray.sampledict)
    new_normalsamples = copy.copy(thisGeneArray.normal_samples)
    newGeneArray = myArray(newExpVal, new_gendict, newsampledict, new_normalsamples, new_genIntr)
    
    return newGeneArray

def create_thisGenearray(expression_matrix, gene_dictionary, sample_dictionary, normal_samples_list, gene_interval_dict):
    return myArray(expression_matrix, gene_dictionary, sample_dictionary, normal_samples_list, gene_interval_dict)
    


def get_gene_subset(thisgenelist, all_genes, all_gene_intervals):
    '''
    It requires that the gene identifiers are unique. Isoforms should be named differently
    '''
    gene_subset = OrderedDict()
    gene_subset_int = OrderedDict()
    gene_subset_rows = OrderedDict()
    gene_array = deque()
    notfound=[]
    i=0
    for gen in thisgenelist:
        try:
            gene_rows = all_genes[gen]
            if not gene_rows:
                continue
            
            gene_interval = all_gene_intervals[gen]
            new_gene_rows=[] 
            
            for p,l in zip(gene_rows,gene_interval):
                gene_subset[gen] = i
                gene_subset_int[i] = l
                gene_array.append(p)
                new_gene_rows.append(i)
                i+=1 
            gene_subset_rows[gen] =  new_gene_rows
                
        except KeyError:
            notfound.append(gen)
    
    return gene_subset, np.array(gene_array), gene_subset_int, gene_subset_rows
 

def get_gene_subset_mod(thisgenelist, all_genes, all_gene_intervals):
        
    gene_subset = OrderedDict()
    gene_subset_int = OrderedDict()
    
    gene_array = deque()
    notfound=[]
    i=0
    for gen in thisgenelist:
        try:
            gene_rows = all_genes[gen]
            gene_interval = all_gene_intervals[gen]
            
            for p,l in zip(gene_rows,gene_interval):
                gene_subset[i] = gen
                gene_subset_int[i] = l
                gene_array.append(p)
                i+=1
                
        except KeyError:
            notfound.append(gen)
    return gene_subset, np.array(gene_array), gene_subset_int
 
 
 
# Deprecated  
def get_sample_subset_dep(thissampleslist, all_samples):
        
    sample_subset = OrderedDict()
    sample_subset2 = OrderedDict()
    sample_array = deque()
    notfound=[]
    j=0
    for sp in thissampleslist:
        try:
            sample_array.append(all_samples[sp])
            sample_subset[j] = sp
            sample_subset2[sp] = j
            j+=1
        except KeyError:
            print 'sample not found ' + sp + str(j)
            notfound.append(sp)
    return sample_subset, np.array(sample_array), sample_subset2


def get_sample_subset(thissampleslist, normalsamples, all_samples):
        
    sample_subset = OrderedDict()
    sp_columns_in_allsamples = deque()
    benign_columns_in_allsamples=deque()
    notfound=[]
    thissampleslist.sort()
    normalsamples.sort()
    sample_test=deque()
    j=0
    for sp in normalsamples:
        try:
            sp_columns_in_allsamples.append(all_samples[sp])
            benign_columns_in_allsamples.append(all_samples[sp])
            sample_subset[j] = sp
            j+=1
            sample_test.append((sp, all_samples[sp]))
        except KeyError:
            print 'sample not found ' + sp + str(j)
            notfound.append(sp)
    
    for sp in thissampleslist:
        try:
            sp_columns_in_allsamples.append(all_samples[sp])
            sample_subset[j] = sp
            j+=1
            sample_test.append((sp, all_samples[sp]))
        except KeyError:
            print 'sample not found ' + sp + str(j)
            notfound.append(sp)
    
    print sample_test
                        
    return sample_subset, sp_columns_in_allsamples, benign_columns_in_allsamples


def read_files_folder(folderpath,ext):
    ''' '''
    # Read files in folder
    myfiles=[]
    for infile in glob.glob( os.path.join(folderpath, '*'+ext+'*.txt') ):
        myfiles.append(infile)
        #print "current file is: " + infile
    return myfiles

def read_files_folder1(folderpath,ext):
    ''' '''
    # Read files in folder
    myfiles=[]
    for infile in glob.glob( os.path.join(folderpath, '*'+ext) ):
        myfiles.append(infile)
        #print "current file is: " + infile
    return myfiles


#read_sample_list(open('/exds/users/oabalbin/projects/druggable/ERBB2_samples_experiment.txt'))